package visitordao

import (
	"database/sql"
	"github.com/sirupsen/logrus"
	"chaoyer/ghost_assist/entity"
	"chaoyer/ghost_assist/base"
)

func FindByPostId(postId string) (entity.Pv, error) {
	var v entity.Pv
	// 先查询数据库是否有文章的访问数
	stmt, err := base.Db.Preparex(`SELECT * FROM tb_pv WHERE post_id = ?`)
	if err != nil {
		logrus.Error(err)
		return v, err
	}

	err = stmt.Get(&v, postId)
	if err != nil {
		if err == sql.ErrNoRows {
			logrus.Info(err)
		} else {
			logrus.Error(err)
		}
		return v, err
	}
	return v, nil
}

func Insert(visitor entity.Pv) (int64, error) {

	stmt, err := base.Db.Preparex("INSERT INTO tb_pv (post_id,pv,created_at,updated_at) values (?,?,now(),now())")
	if err != nil {
		logrus.Error(err)
		return 0, err
	}
	result, err := stmt.Exec(visitor.PostId, 1)
	if err != nil {
		logrus.Error(err)
		return 0, err
	}
	lastInsertId, _ := result.LastInsertId()
	return lastInsertId, nil
}

func UpdatePv(visitor entity.Pv) (int64, error) {
	// pv++
	stmt, err := base.Db.Preparex("UPDATE tb_pv set pv=?,updated_at=now() where post_id = ?")
	if err != nil {
		logrus.Error(err)
		return 0, err
	}
	result, err := stmt.Exec(visitor.Pv+1, visitor.PostId)
	if err != nil {
		logrus.Error(err)
		return 0, err
	}
	effectRowsNum, _ := result.RowsAffected()
	return effectRowsNum, nil
}
